package com.evil.application.pojo.dto.button;

import cn.hutool.core.collection.CollectionUtil;
import com.evil.application.pojo.entity.ApplicationButton;
import com.evil.common.application.dto.judge.JudgeOr;
import com.evil.common.application.dto.permission.app.AppPermissionDTO;
import com.evil.common.application.dto.robot.RobotRuleDTO;
import com.evil.common.application.enums.button.TriggerActionEnum;
import com.evil.common.core.enums.SwitchEnum;
import com.evil.common.family.util.AssertParam;
import lombok.Data;
import lombok.EqualsAndHashCode;

import jakarta.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@Data
@EqualsAndHashCode(callSuper = true)
public class ButtonRespDTO extends ButtonBaseDTO {

    /**
     * 按钮目标应用
     */
    private Long targetApplicationId;

    /**
     * 触发条件 筛选数据(triggerAction为3时值有效)
     */
    @Valid
    private List<JudgeOr> triggerConditions;

    /**
     * 赋值规则配置(triggerAction为1时值有效)
     */
    @Valid
    private List<RobotRuleDTO> robotRules;

    /**
     * 目标应用 筛选数据(triggerAction为3时值有效)
     */
    @Valid
    private List<JudgeOr> judgeOrs;

    /**
     * 权限
     */
    @Valid
    private List<AppPermissionDTO> permissions;

    /**
     * 密码
     */
    private String password;

    public ButtonRespDTO() {
        super();
        this.triggerConditions = new ArrayList<>();
        this.robotRules = new ArrayList<>();
        this.judgeOrs = new ArrayList<>();
        this.permissions = new ArrayList<>();
    }

    public void copyProp(ApplicationButton button) {
        super.copyProp(button);
        // 判断是否有触发条件
        button.setTriggerCondition(SwitchEnum.findByBoolean(CollectionUtil.isNotEmpty(triggerConditions)).getId());
        button.setTargetApplicationId(this.targetApplicationId);
        button.setPassword(this.password);
    }

    public void check() {
        TriggerActionEnum triggerActionEnum = TriggerActionEnum.isExistById(super.getTriggerAction());
        // 跳转链接
        if (TriggerActionEnum.JUMP_LINK == triggerActionEnum) {
            // 如果是跳转链接，跳转链接不能为空
            AssertParam.isTrue(null != super.getLink(), "跳转链接不能为空");
        } else {
            // 添加数据 / 修改数据
            int robotRuleType = triggerActionEnum.getRobotTriggerTypeEnum().getRobotRuleTypeEnum().getId();
            // 目标应用id不能为空
            AssertParam.isTrue(null != this.targetApplicationId, "目标应用不能为空");
            // 规则类型限定
            AssertParam.isTrue(this.robotRules.stream().allMatch(e -> e.getRobotRuleType() == robotRuleType), "规则类型有误");
        }
    }
}
